﻿using System.Threading;

namespace eLoop;

sealed class SingleSyncQueueScheduler : SingleUnsyncQueueScheduler
{
    public SingleSyncQueueScheduler() : base()
    {
    }

    private ASyncContext syncContext;
    
    protected override void InitializationSyncContext()
    {
        this.syncContext = new ThreadSyncContext(this);
    }

    protected override void StartExecute()
    {
        this.SetSyncContext();
        base.StartExecute();
    }

    private void SetSyncContext()
    {
        if (SynchronizationContext.Current is not ThreadSyncContext)
        {
            SynchronizationContext.SetSynchronizationContext(this.syncContext);
        }
    }

    public override void Dispose()
    {
        if (IsDisposed)
        {
            return;
        }

        this.syncContext.Dispose();
        base.Reset();
    }
}